package com.kmxd.ams.infra.ibatis.handler;

import cn.hutool.core.util.BooleanUtil;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * 布尔类型转换
 *
 * @author nickbi
 */
public class BooleanTypeConvert extends BaseTypeHandler<Boolean> {

  @Override
  public void setParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setInt(i, BooleanUtil.isTrue(parameter) ? 1 : 0);
  }

  @Override
  public void setNonNullParameter(
      PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType)
      throws SQLException {
    if (aBoolean) {
      preparedStatement.setInt(i, 1);
    } else {
      preparedStatement.setInt(i, 0);
    }
  }

  @Override
  public Boolean getNullableResult(ResultSet resultSet, String s) throws SQLException {
    int man = resultSet.getInt(s);
    return man == 1;
  }

  @Override
  public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
    int anInt = resultSet.getInt(i);
    return 1 == anInt;
  }

  @Override
  public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
    int man = callableStatement.getInt(i);
    return 1 == man;
  }
}
